﻿using System;
using System.Threading;
using System.Threading.Tasks;
using QuartzUI.Code;

namespace QuartzUI.Service.BackgroundService
{
	public class MessageService : Microsoft.Extensions.Hosting.BackgroundService
    {
        private readonly RabbitMqHelper _rabbitMqHelper;

        public MessageService(RabbitMqHelper rabbitMqHelper)
		{
			_rabbitMqHelper = rabbitMqHelper;
		}
        /// <summary>
        /// 开始执行任务
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            LogHelper.WriteWithTime("开始执行...");
            await base.StartAsync(cancellationToken);
        }

        /// <summary>
        /// 停止执行任务
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            //释放RabbitMq
            _rabbitMqHelper.Dispose();

            LogHelper.WriteWithTime("停止执行...");

            await base.StopAsync(cancellationToken);
        }

        /// <summary>
        /// 处理任务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            async Task handler(string msg, int retrycount, Exception ex)
            {
                LogHelper.WriteWithTime($"重试次数 : {retrycount}，异常 : {ex?.ToString()}");
                await Task.CompletedTask;
            }
            await Task.CompletedTask;
        }
    }
}
